package com.se.utils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class FileChooserService {

    public static String showChooseFileUI(int fileOrDirectory, boolean isImage) {
        AtomicReference<String> path = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean();
        flag.set(false);
        SwingUtilities.invokeLater(() -> {
            JFileChooser fileChooser = new JFileChooser();
            // 设置默认路径（例如用户目录）
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            // 设置对话框标题
            fileChooser.setDialogTitle("选择文件或目录");
            // 设置选择模式（文件、目录、或两者）
            fileChooser.setFileSelectionMode(fileOrDirectory);

            // 添加文件过滤器（例如仅显示图片）
            if(isImage) {
                FileNameExtensionFilter imageFilter = new FileNameExtensionFilter(
                        "图片文件(*.jpg,*.png)", "jpg", "png");
                fileChooser.addChoosableFileFilter(imageFilter);
                fileChooser.setAcceptAllFileFilterUsed(false);
            }

            // 显示打开对话框
            int result = fileChooser.showOpenDialog(null);

            if(result == JFileChooser.APPROVE_OPTION) {
                String selectedPath = fileChooser.getSelectedFile().getAbsolutePath();
                path.set(selectedPath);
            }
            else {
                path.set(null);
            }

            flag.set(true);
        });

        while(!flag.get()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                /*
                无需额外处理
                 */
                e.printStackTrace();
            }
        }

        return path.get();
    }

    public static String getFileName(String path) {
        File file = new File(path);
        return file.getName();
    }

    public static void main(String[] args) {
        System.out.println(showChooseFileUI(JFileChooser.FILES_ONLY, false));
    }
}
